import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Cookies from 'js-cookie'

import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN' // 中文
import elementEnLocale from 'element-ui/lib/locale/lang/en' // 英语
import elementViLocale from 'element-ui/lib/locale/lang/vi' // 越南语
import elementThLocale from 'element-ui/lib/locale/lang/th' // 泰语
// import elementMsLocale from './element-ui/ms' // 马来语

import zhLocale from './zh_CN'
import viLocale from './vi_VN'
import enLocale from './en_US'
import thLocale from './th_TH'

Vue.use(VueI18n)
const outputArrData = []
let outputJsonData = {}

// 'zh_CN', 'en_US', 'vi_VN', 'th_TH'
// 可选语言
const langKeyList = ['zh_CN', 'en_US', 'vi_VN', 'th_TH']

const defaultLangLsit = [
	{ langName: '简体中文', langCode: 'zh_CN' },
	{ langName: 'English', langCode: 'en_US' },
	{ langName: 'Tiếng Việt', langCode: 'vi_VN' },
	{ langName: 'ไทย', langCode: 'th_TH' }
]

function handleJsonData(data, parentKey = '') {
	if (typeof data === 'object') {
		if (Array.isArray(data)) {
			for (const key in data) {
				outputJsonData[parentKey + '.' + key] = data[key].description
			}
		} else {
			for (const key in data) {
				const _key = parentKey ? parentKey + '.' + key : key
				handleJsonData(data[key], _key)
				outputJsonData[parentKey + '.' + key] = data[key]
			}
		}
	}
}

function handleArrData() {
	const langArr = [zhLocale, viLocale, enLocale, thLocale]
	langArr.forEach((data) => {
		outputJsonData = {}
		const jsonData = JSON.parse(JSON.stringify(data))
		handleJsonData(jsonData)
		for (const key in outputJsonData) {
			if (typeof outputJsonData[key] === 'object') {
				delete outputJsonData[key]
			}
		}
		outputArrData.push(outputJsonData)
	})
}

handleArrData()

const messages = {
	zh_CN: {
		...zhLocale,
		...elementZhLocale
	},
	en_US: {
		...enLocale,
		...elementEnLocale
	},
	vi_VN: {
		...viLocale,
		...elementViLocale
	},
	th_TH: {
		...thLocale,
		...elementThLocale
	}
}

export const getLangList = () => {
	return defaultLangLsit.filter((item) => langKeyList.includes(item.langCode))
}

export function getLanguage() {
	for (const key in messages) {
		if (!langKeyList.includes(key)) delete messages[key]
	}

	let language = Cookies.get('language')
	language = messages[language] ? language : defaultLangLsit[0].langCode

	if (!language) {
		language = (
			navigator.language || navigator.browserLanguage
		).toLowerCase()
	}
	Cookies.set('language', language)
	return language
}
const i18n = new VueI18n({
	locale: getLanguage(),
	messages,
	silentTranslationWarn: true
})

export default i18n
